package com.company.control;

import com.company.bean.UserInfoBean;
import com.company.dao.DBProvide;
import com.company.model.UserModel;
import com.company.util.Myutils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

import static com.company.util.Myutils.convertString2Date;

//映射路径
@WebServlet(name = "UserInfoAddServlet", value = "/UserInfoAddServlet")
public class UserInfoAddServlet extends HttpServlet {

    /**
     *
     * 表单数据的保存
     *  页面的跳转
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //1.设置编码
       /*
       request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        */

        //2.获取表单数据，并把表单数据保存到实例类中
        // 【此步功能：将表单数据保存到对应的实体类的属性是上】
        // 【在SpringMVC框架中会自动实现】
        //参考案例：https://gitee.com/climpeaker/zb_webproject0915/blob/master/src/com/yuw/utils/MyUtils.java
        UserInfoBean userInfoBean = Myutils.getNewIntance(UserInfoBean.class);

        //如果有id主键字段的，获取该字段值
        if (StringUtils.isNotEmpty(request.getParameter("userID"))){
            userInfoBean.setUserID(Integer.valueOf(request.getParameter("userID")));
        }

        userInfoBean.setUserName(request.getParameter("userName"));
        System.out.println("用户名："+request.getParameter("userName"));
        userInfoBean.setUserPsw(request.getParameter("userPsw"));
        userInfoBean.setUserPhone(request.getParameter("userPhone"));

        //把从前台野蛮获取的表单数据的值转换为日期Date类型
        String strUserRegisterDate = request.getParameter("userRegisterDate");
        System.out.println("前台页面的日期字符串："+strUserRegisterDate);
        userInfoBean.setUserRegisterDate(Myutils.convertString2Date(strUserRegisterDate,"yyyy-MM-dd"));



        //3.使用model层进行数据保存的业务逻辑
      //  int i = 1;

        int i = Myutils.getNewIntance(UserModel.class).saveUserInfo(userInfoBean);


        //4.数据保存成功之后，跳转的保存结果显示页面
        if (i>0){
            //保存成功后，跳转到成功显示页面

            //调用Model层进行查询操作，将用户数据查询出来，保存到session中
            List<UserInfoBean> listUsers = Myutils.getNewIntance(UserModel.class).queryUserInfoAll();
            //在跳转之前，需要将显示在成功页面的数据进行session缓存
            request.getSession().setAttribute("listUsers",listUsers);

            request.getRequestDispatcher("WEB-INF/viewpages/userinfoB/UserInfoAddDetail.jsp")
                    .forward(request,response);

        }
        else {
            //保存失败，继续跳回到新增页面
            request.getRequestDispatcher("WEB-INF/viewpages/userinfoB/UserInfoAdd.jsp")
                    .forward(request,response);
        }
    }
}
